const {
  ACCOUNT_OR_PASSWORD_IS_REQUIRED,
  ACCOUNT_IS_NOT_EXISTS,
  PASSWORD_IS_INCORRECT,
  UNAUTHORIZATION
} = require("../config/error")
const userService = require("../service/user.service")
const md5Password = require("../utils/md5-password")
const { PUBLIC_KEY } = require('../config/screct')
const jwt = require('jsonwebtoken')

const verifyLogin = async (ctx, next) => {
  const { account, password } = ctx.request.body

  // 1.判断账号和密码是否为空
  if (!account || !password) {
    return ctx.app.emit('error', ACCOUNT_OR_PASSWORD_IS_REQUIRED, ctx)
  }

  // 2.查询该用户是否在数据库中存在
  const users = await userService.findUserByAccount(account)
  const user = users[0]
  if (!user) {
    return ctx.app.emit('error', ACCOUNT_IS_NOT_EXISTS, ctx)
  }

  // 3.查询数据库中密码和用户传递的密码是否一致
  const md5Pwd = md5Password(password)
  if (user.password !== md5Pwd) {
    return ctx.app.emit('error', PASSWORD_IS_INCORRECT, ctx)
  }

  // 4.将user对象保存在ctx中
  ctx.user = user

  await next()
}

const verifyAuth = async (ctx, next) => {
  // 1.获取传过来的token
  const { authorization } = ctx.request.header
  if (!authorization) {
    return ctx.app.emit('error', UNAUTHORIZATION, ctx)
  }

  const token = authorization.replace('Bearer ', '')

  // 2.验证token是否有效
  try {
    // 2.1.获取token信息
    const result = jwt.verify(token, PUBLIC_KEY, {
      algorithms: ['RS256']
    })

    // 2.2.将token的信息保留下来
    ctx.user = result

    // 3.执行下一个中间件
    await next()

  } catch(error) {
    console.error('Error verifying token: ', error)
    ctx.app.emit('error', UNAUTHORIZATION, ctx)
  }
}

module.exports = {
  verifyLogin,
  verifyAuth
}